package cn.iocoder.yudao.module.reading.service.book;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.module.reading.controller.app.book.vo.BookPageRespVO;
import cn.iocoder.yudao.module.reading.controller.app.book.vo.PictureBookDetailRespVO;
import cn.iocoder.yudao.module.reading.dal.dataobject.book.BookPageDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.book.PictureBookDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.bookset.BookSetDO;
import cn.iocoder.yudao.module.reading.dal.dataobject.record.ReadingRecordDO;
import cn.iocoder.yudao.module.reading.dal.mysql.book.BookPageMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.book.PictureBookMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.bookset.BookSetMapper;
import cn.iocoder.yudao.module.reading.dal.mysql.record.ReadingRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import jakarta.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.reading.enums.ErrorCodeConstants.PICTURE_BOOK_NOT_EXISTS;

/**
 * 绘本 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class PictureBookServiceImpl implements PictureBookService {

    @Resource
    private PictureBookMapper pictureBookMapper;
    @Resource
    private BookPageMapper bookPageMapper;
    @Resource
    private BookSetMapper bookSetMapper;
    @Resource
    private ReadingRecordMapper readingRecordMapper;

    @Override
    public PictureBookDO getPictureBook(Long id) {
        PictureBookDO pictureBook = pictureBookMapper.selectById(id);
        if (pictureBook == null) {
            throw exception(PICTURE_BOOK_NOT_EXISTS);
        }
        return pictureBook;
    }

    @Override
    public PictureBookDetailRespVO getPictureBookDetail(Long id, Long userId) {
        // 1. 获取绘本信息
        PictureBookDO pictureBook = getPictureBook(id);
        
        // 2. 获取绘本集信息
        BookSetDO bookSet = bookSetMapper.selectById(pictureBook.getBookSetId());
        
        // 3. 获取绘本页面列表
        List<BookPageDO> pages = bookPageMapper.selectByBookId(id);
        
        // 4. 获取用户阅读记录
        ReadingRecordDO readingRecord = null;
        if (userId != null) {
            readingRecord = readingRecordMapper.selectByUserIdAndBookId(userId, id);
        }
        
        // 5. 构建响应
        PictureBookDetailRespVO result = new PictureBookDetailRespVO();
        result.setId(pictureBook.getId());
        result.setTitle(pictureBook.getTitle());
        result.setCover(pictureBook.getCover());
        result.setPages(pictureBook.getPages());
        result.setSortOrder(pictureBook.getSortOrder());
        result.setBookSetId(pictureBook.getBookSetId());
        result.setBookSetTitle(bookSet != null ? bookSet.getTitle() : null);
        
        // 6. 设置阅读状态
        PictureBookDetailRespVO.ReadStatusVO readStatus = new PictureBookDetailRespVO.ReadStatusVO();
        if (readingRecord != null) {
            readStatus.setIsRead(readingRecord.getIsCompleted());
            readStatus.setReadCount(1); // 简化处理
            readStatus.setLastReadAt(readingRecord.getLastReadAt() != null ? readingRecord.getLastReadAt().toString() : null);
            readStatus.setReadProgress(readingRecord.getReadingProgress());
            readStatus.setLastPage(readingRecord.getLastPage());
            readStatus.setReadingTime(readingRecord.getReadingTime());
        } else {
            readStatus.setIsRead(false);
            readStatus.setReadCount(0);
            readStatus.setLastReadAt(null);
            readStatus.setReadProgress(0.0);
            readStatus.setLastPage(0);
            readStatus.setReadingTime(0);
        }
        result.setReadStatus(readStatus);
        
        // 7. 设置页面列表
        if (CollUtil.isNotEmpty(pages)) {
            List<PictureBookDetailRespVO.BookPageRespVO> pageList = pages.stream().map(page -> {
                PictureBookDetailRespVO.BookPageRespVO pageVO = new PictureBookDetailRespVO.BookPageRespVO();
                pageVO.setId(page.getId());
                pageVO.setPageNumber(page.getPageNumber());
                pageVO.setImageUrl(page.getImageUrl());
                pageVO.setTextContent(page.getTextContent());
                pageVO.setChineseTranslation(page.getChineseTranslation());
                pageVO.setOfficialAudioUrl(page.getOfficialAudioUrl());
                // 用户音频URL需要单独查询用户配音记录
                return pageVO;
            }).collect(Collectors.toList());
            result.setPageList(pageList);
        }

        // 8. 转换URL
        result.convertUrls();

        return result;
    }

}
